package com.txy.springcloud.controller;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.txy.springcloud.service.TxyServiceEmailFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;

@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private TxyServiceEmailFeignClient emailClient;


    @Autowired
    private ComboPooledDataSource dataSource;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // curl "http://127.0.0.1:8081/code/create/2389679202@qq.com"
    @PostMapping("/create/{email}")
    public boolean create(@PathVariable("email") String email) {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 生成验证码
                    String code = create();
                    // 存数据库
                    saveCode(email, code);
                    // 发送邮箱
                    emailClient.sendCode(email, code);

                }
            }).start();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @PostMapping("/validate/{email}/{code}")
    public int validate(@PathVariable("email") String email, @PathVariable("code") String code) {
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, -10);
            PreparedStatement preparedStatement = dataSource.getConnection().prepareStatement("select * from verification_code where email = ? and value = ? and createTime > ?");
            preparedStatement.setString(1, email);
            preparedStatement.setString(2, code);
            preparedStatement.setString(3, sdf.format(calendar.getTime()));
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return 1;
    }



    private static final Random random = new Random();

    private static final Integer END = 10;

    private static final Integer CAPTCHA_LENGTH = 6;//验证码长度，nextDouble()方法生成的数字精确到小数点后16位，所以验证码长度最大可以到16位。

    private String create() {
        Double pross = random.nextDouble() * Math.pow(END, CAPTCHA_LENGTH);
        String captcha = String.format("%06.0f", pross);
        return captcha;
    }

    private void saveCode(String email, String code) {
        try {
            PreparedStatement preparedStatement = dataSource.getConnection().prepareStatement("insert into verification_code(email, `value`) values (?, ?) ON DUPLICATE KEY UPDATE `value`= ?, createTime = now()");
            preparedStatement.setString(1, email);
            preparedStatement.setString(2, code);
            preparedStatement.setString(3, code);
            preparedStatement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
